package com.skymxc.demo.explorer.adapter;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.skymxc.demo.explorer.R;
import com.skymxc.demo.explorer.core.FileType;
import com.skymxc.demo.explorer.util.FileUtil;
import com.skymxc.demo.explorer.util.SettingUtil;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by sky-mxc
 */

public class FileAdapter extends BaseAdapter {

    private static final String TAG ="FileAdapter";

    private List<File> files;
    private LayoutInflater lif;
    private Context mContext;
    private boolean isRoot = true;
    private Picasso picasso;
    private List<File> selectedFiles = new LinkedList<>();
    private OnSelectedChangedListener selectedChangeListener;

    public FileAdapter(Context context,List<File> files){
        this.files=files;
        this.mContext=context;
        lif = LayoutInflater.from(context);
        picasso = Picasso.with(context);
    }

    public void setSelectedChangeListener(OnSelectedChangedListener selectedChangeListener) {
        this.selectedChangeListener = selectedChangeListener;
    }

    public void setFiles(List<File> files) {
        this.files = files;
        notifyDataSetChanged();
    }

    public void setRoot(boolean root) {
        isRoot = root;
    }

    @Override
    public int getCount() {
        return files==null?0:files.size();
    }

    @Override
    public File getItem(int position) {
        return files.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public int getItemViewType(int position) {

        return SettingUtil.getShowMode(mContext);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder =null;
        //显示模式的判断
        int type = getItemViewType(position);
       if (convertView == null ){
          holder = onCreateViewHolder(position,type);
           convertView = holder.itemView;
       }else{
           holder = (ViewHolder) convertView.getTag();
          // Log.e(TAG,"holder.itemViewType:"+holder.itemViewType+"====viewType:"+type);
           if((holder.itemViewType == 2 && type!=2) ||(holder.itemViewType != 2 && type == 2)){
               //详细模式和简略模式 都使用同一holder和布局
               holder = onCreateViewHolder(position,type);
               convertView = holder.itemView;
           }else{
               holder.itemViewType=type;
           }
       }
        //绑定数据
        onBindViewHolder(holder,position);

        return convertView;
    }


    private void setCheckBox(CheckBox checkBox,File file){
        if (selectedFiles.isEmpty()) {
            checkBox.setVisibility(View.INVISIBLE);
            checkBox.setOnCheckedChangeListener(null);
            checkBox.setChecked(false);

            return;

        }
        checkBox.setVisibility(View.VISIBLE);
        checkBox.setTag(file);
        checkBox.setOnCheckedChangeListener(null);
       // Log.e(TAG,"===fileName:"+file.getName()+"===checked:"+selectedFiles.contains(file));
        if (selectedFiles.contains(file)){
            checkBox.setChecked(true);
        }else{
            checkBox.setChecked(false);
        }
        // checkBox.setChecked(selectedFiles.contains(file));
        checkBox.setOnCheckedChangeListener(checkedChangeLis);
    }

    /**
     * 设置选中和不选中
     * @param position
     */
    public void toggleSelectFile(int position){
        if (!isRoot && position ==0) return;
        File file = getItem(position);

        if (selectedFiles.contains(file)){
            selectedFiles.remove(file);
        }else{
            selectedFiles.add(file);
        }
        if (selectedChangeListener!=null){
            selectedChangeListener.onSelectedChanged(new ArrayList<>(selectedFiles));
        }
        notifyDataSetChanged();
    }


    /**
     * 为view绑定数据
     * @param holder
     * @param position
     */
    private void onBindViewHolder(ViewHolder holder, int position) {
        File file = getItem(position);
        if( holder instanceof ListHolder){
            ListHolder lh = (ListHolder) holder;
            if (!isRoot && position == 0){//不是根节点
                lh.tvTitle.setText("返回上一级");
                lh.icon.setImageResource(R.mipmap.folder_yellow);
                lh.tvInfo.setVisibility(View.INVISIBLE);
                lh.check.setVisibility(View.GONE);
            }else{//根节点
                lh.tvTitle.setText(file.getName());
                setIcon(file,lh.icon);
                lh.check.setVisibility(View.VISIBLE);
                if (holder.itemViewType == 0){//详细模式
                    lh.tvInfo.setVisibility(View.VISIBLE);
                    lh.tvInfo.setText(FileUtil.getFileInfo(mContext, file));
                }else{//简略模式
                    lh.tvInfo.setVisibility(View.GONE);
                }
                setCheckBox(lh.check,file);
            }

        }else{
            GridHolder gh = (GridHolder) holder;
            if (!isRoot && position == 0){
                gh.tvTitle.setText("·········");
               // gh.icon.setImageResource(R.mipmap.folder_yellow);
                setIcon(file,gh.icon);
                gh.check.setVisibility(View.GONE);
            }else {
                gh.tvTitle.setText(file.getName());
                setIcon(file,gh.icon);
                setCheckBox(gh.check,file);
            }
        }
    }

    /**
     * 设置文件图标
     * @param file
     * @param imageView
     */
    private void setIcon(File file ,ImageView imageView){
        if (FileType.parseFile(file)==FileType.IMAGE && SettingUtil.isShowImageThumb(mContext)){
            //图片
            Log.d(TAG,"setIcon  === filePath=:"+file.getPath()+"===uri:"+Uri.fromFile(file));
            picasso.load( Uri.fromFile(file))
                    .placeholder(R.mipmap.image)
                    .error(R.mipmap.ic_launcher)
                    .resize(R.dimen.grid_item_icon_width,R.dimen.grid_item_icon_height)
                    .into(imageView);
//            FileInputStream fis =null;
//            ByteArrayOutputStream bos =null;
//            try {
//                fis=new FileInputStream(file);
//                bos = new ByteArrayOutputStream();
//                int len ;
//                byte[] b = new byte[1024];
//                while ((len=fis.read(b))!=-1){
//                    bos.write(b,0, len);
//                }
//
//                bos.flush();
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//                try {
//                    if (bos!=null)
//                         bos.close();
//                    if (fis !=null)
//                        fis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            // Bitmap bmp= BitmapFactory.decodeByteArray(bos.toByteArray(),0,bos.size());
//            Bitmap bmp=   BitmapFactory.decodeFile(file.getPath());
//            imageView.setImageBitmap(bmp);

        }else{
            imageView.setImageResource(FileUtil.getIcon(file));
        }
    }


    /**
     * 根据不同的显示模式创建不同的Holder
     * @param position
     * @param viewType
     * @return
     */
    private ViewHolder onCreateViewHolder(int position,int viewType){
        ViewHolder holder =null;
        switch (viewType){
            case 0://详细
            case 1://简单
                holder = new ListHolder(lif.inflate(R.layout.layout_list_item,null));
                break;
            case 2://网格
                holder = new GridHolder(lif.inflate(R.layout.layout_grid_item,null));
                break;
        }
        if (holder != null)
        holder.itemViewType =viewType;
        return  holder;
    }


    /**
     * 当前是否有文件选中
     * @return
     */
    public boolean isSelectFileStatus() {
        return  !selectedFiles.isEmpty();
    }

    private CompoundButton.OnCheckedChangeListener checkedChangeLis = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            File file = (File) buttonView.getTag();
            if (isChecked){
                selectedFiles.add(file);
            }else{
                selectedFiles.remove(file);
            }
            if (selectedChangeListener!=null){
                selectedChangeListener.onSelectedChanged(new ArrayList<>(selectedFiles));
            }

            if (selectedFiles.isEmpty())
                notifyDataSetChanged();
        }
    };

    /**
     * 清除全部选中
     */
    public void clearAllSelected() {
        selectedFiles.clear();
        notifyDataSetChanged();
    }

    public void selectAll() {
        selectedFiles.clear();
        selectedFiles.addAll(files);
        if (!isRoot){
            selectedFiles.remove(0);
        }
        selectedChangeListener.onSelectedChanged(new ArrayList<>(selectedFiles));
       notifyDataSetChanged();
    }

    public interface  OnSelectedChangedListener{
        void onSelectedChanged(List<File> selectedFiles);
    }


    class  ViewHolder{
        View itemView;
        int itemViewType;
        public ViewHolder(View itemView) {
            this.itemView = itemView;
            this.itemView.setTag(this);
        }
    }





    class  ListHolder extends ViewHolder{
        ImageView icon;
        TextView tvTitle;
        TextView tvInfo;
        CheckBox check;
        public ListHolder(View view){
            super(view);
            icon = (ImageView) view.findViewById(R.id.list_item_icon);
            tvTitle = (TextView) view.findViewById(R.id.list_item_title);
            tvInfo = (TextView) view.findViewById(R.id.list_item_info);
            check = (CheckBox) view.findViewById(R.id.lite_item_check);
        }
    }

    class GridHolder extends ViewHolder{
        ImageView icon;
        TextView tvTitle;
        CheckBox check;
        public GridHolder(View view){
            super(view);
            icon = (ImageView) view.findViewById(R.id.list_item_icon);
            tvTitle = (TextView) view.findViewById(R.id.list_item_title);
            check = (CheckBox) view.findViewById(R.id.lite_item_check);
        }
    }


}
